import siyuan from "siyuan";
import * as other from "../test/other";
//import { testHtml } from "./testHtml";
//import { BlockPanel } from "./Panel";
//import { MenuItem, IMenuItemOption } from "siyuan/internal/classes/menu";
//!经测试，插件是在document load 后加载的
export default class SiyuanSamplePlugin extends Plugin {
  constructor() {
    super();
  }

  onload() {
    //other.example();
    console.clear();
    let blockId: string | null;
    window.addEventListener("mousedown", (event) => {
      let ele: Element | null;
      blockId = getBlockOnEvent(event);
      if (blockId) {
        ele = 获取指定id元素(blockId);
        console.log(ele);
      }
      let plainEle = document.createElement("div");
    });
  }
  onunload() {
    console.log("plugin unload");
  }
}
function getBlockOnEvent(event: MouseEvent): string | null {
  //todo 可以直接用 event.target
  //console.log(event);
  let x = event.clientX;
  let y = event.clientY;
  let element = document.elementFromPoint(x, y);
  if (!element) {
    return null;
  }
  let dataNodeId: string | null;
  let parent = element.parentElement as HTMLElement;
  if (element.tagName == "BUTTON") {
    dataNodeId = element.getAttribute("data-node-id");
    if (dataNodeId) {
      return dataNodeId;
    }
  }
  if (parent.tagName == "BUTTON") {
    dataNodeId = parent.getAttribute("data-node-id");
    if (dataNodeId) {
      return dataNodeId;
    }
  }
  return null;
}

function 向工具栏添加元素() {
  let button = document.createElement("button");
  button.innerText = "Hello World";
  siyuan.clientApi.addToolbarRight(button);
  return button;
}

function 向工具栏添加按钮且附加菜单() {
  const button = document.createElement("button");
  button.textContent = "left";
  button.addEventListener("click", (event) => {
    new siyuan.Menu("internalSettingButton")
      .addItem(
        new MenuItem({
          label: "Hello World",
          icon: "iconEdit",
          click: () => console.log("hello world"),
        })
      )
      .showAtMouseEvent(event);
    event.stopPropagation();
  });
  siyuan.clientApi.addToolbarLeft(button);
}
// todo 使用思源menuItem
//*以向块菜单添加为例
function 监听菜单变化并向其添加元素(label: string) {
  // @ts-ignore
  let menuEle: Element = window.siyuan.menus.menu.element;
  let button = menuItem(label);
  const config = {
    attributes: false,
    childList: true,
    subtree: false,
    //attributeFilter: ["class"],
    //attributeOldValue: true,
  };
  const observer = new MutationObserver((mutationsList, observer) => {
    //console.log(mutationsList);
    if (!mutationsList[0].addedNodes) {
      return;
    }
    for (let mutations of mutationsList) {
      //!必须循环遍历，只在某一项添加后添加这一项，否则会陷入死循环
      //todo 既做位置，又做判断是块菜单的条件,但是没有其他方法了么？
      let lastBrother = mutations.addedNodes[0] as HTMLElement;
      if (!lastBrother) {
        continue;
      }
      if (lastBrother.classList.contains("b3-menu__item--readonly")) {
        menuEle.insertBefore(button, lastBrother);
        break;
      }
    }
    return;
  });
  observer.observe(menuEle, config); //开始监听
  return;
}
function menuItem(label: string): HTMLElement {
  let div = document.createElement("div") as HTMLElement;
  div.innerHTML =
    //html
    `<button class="b3-menu__item">
      <svg class="b3-menu__icon" style="">
          <use xlink:href="#"></use>
      </svg>
      <span class="b3-menu__label">${label}</span>
        </button>`;
  let button = div.firstElementChild as HTMLElement;
  return button;
}

function 监听block前protyle_gutters() {
  let tabContainer = document.querySelector(".layout__center") as HTMLElement;
  console.log(tabContainer);
  const config = {
    attributes: false,
    childList: true,
    subtree: true,
    //attributeFilter: ["class"],
    //attributeOldValue: true,
  };
  const observer = new MutationObserver((mutationsList, observer) => {
    console.log(mutationsList);
  });
  observer.observe(tabContainer, config); //开始监听
}

function 获取指定id元素(dataNodeId: string) {
  return document.querySelector(`div[data-node-id='${dataNodeId}']`);
}

//!创建后就会弹出
async function dialog测试(htmlText) {
  const dialog = new siyuan.Dialog({
    title: "测试弹出窗口",
    content: "测试内容",
  });
  let container = dialog.element.querySelector(".b3-dialog__container");
  if (!container) {
    console.log("无container");
    return;
  }
  //自定义内容
  //!自定义内容不能取得良好效果，最好使用block__popover
  let ele = document.createElement("div") as Element; //获取指定id元素("20230410210411-gy8ilsm") as HTMLElement;
  //let style = window.getComputedStyle(ele);
  //console.log(style)
  ele.innerHTML = htmlText;
  //console.log(window.getComputedStyle(ele));
  let firstChild = ele.children[0] as Element;
  console.log(firstChild);
  container.appendChild(firstChild);
}

// todo未完成
//let newEle = document.createElement("div");
function 思源块转普通元素(ele: Element, newEle: Element) {
  for (let child of ele.children) {
    let dataType = child.getAttribute("data-type");
    let subType = child.getAttribute("subtype");
    let eleType = "";
    if (dataType) {
      eleType = dataTypes[dataType];
    }
    if (!eleType) {
      newEle.appendChild(child.cloneNode());
      //div2ele()
      continue;
    }

    let typeOfchild;
  }
  return;
}
//\kernel\treenode\node.go(翻转)
const typeAbbrMap = {
  // 块级元素
  d: "NodeDocument",
  h: "NodeHeading",
  l: "NodeList",
  i: "NodeListItem",
  c: "NodeCodeBlock",
  m: "NodeMathBlock",
  t: "NodeTable",
  b: "NodeBlockquote",
  s: "NodeSuperBlock",
  p: "NodeParagraph",
  html: "NodeHTMLBlock",
  query_embed: "NodeBlockQueryEmbed",
  ial: "NodeKramdownBlockIAL",
  iframe: "NodeIFrame",
  widget: "NodeWidget",
  tb: "NodeThematicBreak",
  video: "NodeVideo",
  audio: "NodeAudio",
  text: "NodeText",
  img: "NodeImage",
  link_text: "NodeLinkText",
  link_dest: "NodeLinkDest",
  textmark: "NodeTextMark",
};

//data-type,subtype=>nodeName
const dataTypes = {
  NodeHeading: {
    h1: "H1",
    h2: "H2",
    h3: "H3",
    h4: "H4",
    h5: "H5",
    h6: "H6",
  },
  NodeList: {
    u: "UL",
    o: "OL",
    t: "UL",
  },
  NodeListItem: "LI",
  NodeCodeBlock: "PRE",
  NodeMathBlock: "PRE",
  NodeParagraph: "P",
  NodeTable: "TABLE",
  NodeBlockquote: "BLOCKQUOTE",
  NodeSuperBlock: "DIV",
  NodeHTMLBlock: "",
};
// todo
/* 
  s: "NodeSuperBlock",
  html: "NodeHTMLBlock",
  query_embed: "NodeBlockQueryEmbed",
  ial: "NodeKramdownBlockIAL",
  iframe: "NodeIFrame",
  widget: "NodeWidget",
  tb: "NodeThematicBreak",
  video: "NodeVideo",
  audio: "NodeAudio",
  text: "NodeText",
  img: "NodeImage",
  link_text: "NodeLinkText",
  link_dest: "NodeLinkDest",
  textmark: "NodeTextMark",
};*/
